package com.example.basic_ui_demo.view.teams

import android.os.Build
import androidx.annotation.RequiresApi
import androidx.annotation.RequiresExtension
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.basic_ui_demo.R
import com.example.basic_ui_demo.companion.ApiViewModel
import com.example.basic_ui_demo.companion.calculateAge
import com.example.basic_ui_demo.companion.data.RetrofitInstance
import com.example.basic_ui_demo.data_class.teams.Coach
import com.example.basic_ui_demo.data_class.teams.Squad
import com.example.basic_ui_demo.data_class.teams.Team
import com.example.basic_ui_demo.view_model.TeamsViewModel
import com.lt.compose_views.pager_indicator.TextPagerIndicator

@RequiresExtension(extension = Build.VERSION_CODES.S, version = 7)
@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun SquadCompose(viewModel: TeamsViewModel, team: Team?, teamId: Int) {
    var isLoading by remember { mutableStateOf(true) }
    //加载指示器

    var isError by remember { mutableStateOf(false) }
    //error指示器

    val curSeason by viewModel.season
    //当前赛季

    var coach by remember { mutableStateOf<Coach?>(null) }

    val squadList = remember { mutableStateListOf<Squad>() }

    val squadGroups = remember { mutableStateMapOf<String, List<Squad>>() }

    LaunchedEffect(Unit) {
        isLoading = true
        if (team == null) {
            val api = RetrofitInstance.api
            val newTeam = ApiViewModel.callApi {
                api.getTeamById(teamId, curSeason)
            }
            isError = newTeam?.let {
                coach = it.coach
                squadList.addAll(it.squad)
                false
            } ?: true
        } else {
            squadList.addAll(team.squad)
        }
        isLoading = false
    }

    LaunchedEffect(curSeason) {
        isLoading = true
        if (team == null) {
            val api = RetrofitInstance.api
            val newTeam = ApiViewModel.callApi {
                api.getTeamById(teamId, curSeason)
            }
            isError = newTeam?.let {
                coach = it.coach
                squadList.addAll(it.squad)
                false
            } ?: true
        } else {
            squadList.addAll(team.squad)
        }
        squadGroups.putAll(
            squadList.groupBy { it.position }
        )
        isLoading = false
    }
    LazyColumn(
        contentPadding = PaddingValues(top = 120.dp)
    ) {
        item {
            TextPagerIndicator(
                texts = TeamsViewModel.tabs,
                offsetPercentWithSelectFlow = viewModel.composePagerState.createChildOffsetPercentFlow(),
                selectIndexFlow = viewModel.composePagerState.createCurrSelectIndexFlow(),
                fontSize = 16.sp,
                selectFontSize = 16.sp,
                textColor = Color.Black,
                selectTextColor = Color.Green,
                selectIndicatorColor = Color.Green,
                onIndicatorClick = { viewModel.composePagerState.setPageIndexWithAnimate(it) },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(30.dp),
                userCanScroll = true,
                margin = 20.dp,
            )
        }

        if (isLoading)
            item {
                CircularProgressIndicator()
            }
        else if (isError)
            item {
                CircularProgressIndicator()
            }
        else {
            item { CoachHeader() }
            item { coach?.let { CoachRow(it) } }
            squadGroups.forEach { (position, squads) ->
                item { SquadHeader(position) }
                items(squads){
                    SquadRow(it)
                }
            }
        }
    }
}

@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun CoachRow(coach: Coach) {
    Row(
        Modifier
            .height(40.dp)
            .padding(10.dp)
    ) {
        Row(Modifier.weight(3f)) {
            Image(
                painter = painterResource(id = R.drawable.head),
                contentDescription = null,
                modifier = Modifier
                    .fillMaxHeight()
                    .aspectRatio(1f / 1f)
            )
            Text(text = coach.name)
        }
        Text(modifier = Modifier.weight(1f), text = "${calculateAge(coach.dateOfBirth)}岁")
        Text(modifier = Modifier.weight(2f), text = coach.nationality)
    }
}

@Composable
fun CoachHeader() {
    Row(
        Modifier
            .height(40.dp)
            .padding(10.dp)
            .background(Color.LightGray)
    ) {
        Text(modifier = Modifier.weight(3f), text = "教练")
        Text(modifier = Modifier.weight(1f), text = "年龄")
        Text(modifier = Modifier.weight(2f), text = "国籍", textAlign = TextAlign.Center)
    }
}

@Composable
fun SquadHeader(position: String) {
    val positionName = when (position) {
        "Goalkeeper" -> "守门员"
        "Defence" -> "后卫"
        "Midfield" -> "中场"
        "Offence" -> "前锋"
        else -> "其他"
    }
    Row(
        Modifier
            .height(40.dp)
            .padding(10.dp)
            .background(Color.LightGray)
    ) {
        Text(modifier = Modifier.weight(3f), text = positionName)
        Text(modifier = Modifier.weight(1f), text = "年龄")
        Text(modifier = Modifier.weight(2f), text = "国籍", textAlign = TextAlign.Center)
    }
}

@RequiresApi(Build.VERSION_CODES.O)
@Composable
fun SquadRow(squad: Squad) {
    Row(
        Modifier
            .height(40.dp)
            .padding(10.dp)
    ) {
        Row(Modifier.weight(3f)) {
            Image(
                painter = painterResource(id = R.drawable.head),
                contentDescription = null,
                modifier = Modifier
                    .fillMaxHeight()
                    .aspectRatio(1f / 1f)
            )
            Text(text = squad.name)
        }
        Text(modifier = Modifier.weight(1f), text = "${calculateAge(squad.dateOfBirth)}岁")
        Text(modifier = Modifier.weight(2f), text = squad.nationality, textAlign = TextAlign.Center)
    }
}